//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { CSSProperties, useState } from 'react';
import { Handle, NodeProps, NodeResizer, Position } from 'reactflow';
import type { NodeInfo } from '@/api/roadmap_content';
import { NODE_ROADMAP_REF, NODE_SUB_TOPIC, NODE_TOPIC, NODE_WEB_LINK } from '@/api/roadmap_content';
import { observer } from 'mobx-react';
import { useRoadmapStores } from '../../store';
import { Button, Checkbox, message, Popover, Space } from 'antd';
import { request } from '@/utils/request';
import { get as get_roadmap } from "@/api/roadmap";
import { openRoadmapView } from '@/utils/roadmap';
import { open as shell_open } from '@tauri-apps/api/shell';
import { DeleteOutlined, EditOutlined, MoreOutlined } from '@ant-design/icons';



export interface NodeWrapProps {
    hasHandle: boolean;
    nodeData: NodeProps<NodeInfo>;
    style?: CSSProperties;
    children?: React.ReactNode;
    leftTipText?: string;
    leftTipBgColor?: string;
    rightTipText?: string;
    rightTipText2?: React.ReactNode;
}

const NodeWrap = (props: NodeWrapProps) => {
    const roadmapStore = useRoadmapStores();

    const [hover, setHover] = useState(false);

    const openRoadmap = async (roadmapId: string) => {
        let roadmapName = "";
        try {
            const res = await request(get_roadmap({
                session_id: roadmapStore.sessionId,
                roadmap_id: roadmapId,
            }));
            if (res.roadmap.pub_state == false) {
                message.warn("没有权限访问路线图");
                return;
            }
            roadmapName = res.roadmap.basic_info.title;
        } catch (e) {
            console.log(e);
            message.warn("没有权限访问路线图");
        }
        await openRoadmapView(roadmapId, roadmapName, roadmapStore.sessionId, roadmapStore.adminUser, false);
        message.info("打开路线图成功");
    };

    return (
        <div style={{
            ...(props.style ?? {}),
            width: props.nodeData.data.basic_info.node_size.w,
            height: props.nodeData.data.basic_info.node_size.h,
            position: "relative",
            border: roadmapStore.selectNodeId == props.nodeData.data.node_id ? "3px dashed #666" : props.style?.border,
            cursor: roadmapStore.inEdit ? undefined : "pointer",
        }}
            onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
            onClick={() => {
                if (roadmapStore.inEdit) {
                    return;
                }
                if ([NODE_TOPIC, NODE_SUB_TOPIC].includes(props.nodeData.data.basic_info.node_type) && roadmapStore.adminUser == false) {
                    roadmapStore.selectNodeId = props.nodeData.data.node_id;
                } else if (NODE_ROADMAP_REF == props.nodeData.data.basic_info.node_type) {
                    const targetId = props.nodeData.data.basic_info.node_data.RoadmapRefData?.target_id ?? "";
                    if (targetId == "") {
                        message.warn("未引用路线图");
                    } else {
                        openRoadmap(targetId);
                    }
                } else if (NODE_WEB_LINK == props.nodeData.data.basic_info.node_type) {
                    const linkUrl = props.nodeData.data.basic_info.node_data.WebLinkData?.link_url ?? "";
                    if (linkUrl != "") {
                        if (linkUrl.startsWith("http://") || linkUrl.startsWith("https://")) {
                            shell_open(linkUrl);
                        } else {
                            shell_open(`https://${linkUrl}`);
                        }
                    }
                }
            }}>
            {props.leftTipText != undefined && props.leftTipBgColor != undefined && (
                <div style={{
                    position: "absolute", top: "-10px", left: "6px", fontSize: "10px", zIndex: 4000,
                    borderRadius: "6px", padding: "0px 4px", backgroundColor: props.leftTipBgColor, color: "white", fontWeight: 600
                }}>
                    {props.leftTipText}
                </div>
            )}
            {roadmapStore.inEdit == true && (
                <Space size="small"
                    style={{
                        position: "absolute", top: "-10px", right: "6px", fontSize: "10px", zIndex: 4000,
                        borderRadius: "6px", padding: "0px 4px", backgroundColor: "white", fontWeight: 600,
                    }}>
                    <a onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        roadmapStore.selectNodeId = props.nodeData.data.node_id;
                    }}><EditOutlined /></a>
                    <Popover placement='top' trigger="click" content={
                        <Space direction='vertical'>
                            <Button type="link" danger icon={<DeleteOutlined />}
                                onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    roadmapStore.removeNode(props.nodeData.data.node_id);
                                }}>删除</Button>
                        </Space>
                    }>
                        <MoreOutlined />
                    </Popover>
                </Space>
            )}
            {roadmapStore.inEdit == false && props.rightTipText != undefined && (
                <div
                    style={{
                        position: "absolute", top: "-10px", right: "6px", fontSize: "10px", zIndex: 4000,
                        borderRadius: "6px", padding: "0px 4px", backgroundColor: "grey", color: "white", fontWeight: 600
                    }}>
                    {props.rightTipText}
                </div>
            )}

            {roadmapStore.inEdit && props.rightTipText2 != undefined && (
                <div
                    style={{
                        position: "absolute", bottom: "-10px", right: "6px", fontSize: "10px", zIndex: 4000,
                        borderRadius: "6px", padding: "0px 4px", backgroundColor: "white", fontWeight: 600
                    }}>
                    {props.rightTipText2}
                </div>
            )}

            {roadmapStore.inEdit == false && props.rightTipText2 != undefined && (
                <div
                    style={{
                        position: "absolute", bottom: "2px", left: "6px", fontSize: "10px", zIndex: 4000,
                        borderRadius: "6px", padding: "0px 4px", backgroundColor: "white", fontWeight: 600
                    }}>
                    {props.rightTipText2}
                </div>
            )}

            {roadmapStore.inEdit && roadmapStore.lockSizeAndPosition == false && (
                <Checkbox checked={roadmapStore.batchNodeIdList.includes(props.nodeData.data.node_id)} style={{ position: "absolute", bottom: "-10px", left: "6px", zIndex: 4000 }}
                    onChange={e => {
                        e.stopPropagation();
                        if (e.target.checked) {
                            roadmapStore.addBatchNodeId(props.nodeData.data.node_id);
                        } else {
                            roadmapStore.removeBatchNodeId(props.nodeData.data.node_id);
                        }
                    }} onClick={e => {
                        e.stopPropagation();
                    }} />
            )}

            {roadmapStore.inEdit && hover && roadmapStore.batchNodeIdList.includes(props.nodeData.data.node_id) == false && (
                <NodeResizer minWidth={100} minHeight={40} handleStyle={{ width: "10px", height: "10px", backgroundColor: "black" }} />
            )}

            {props.hasHandle == true && (
                <>
                    <Handle type="source" position={Position.Left} id="l" style={{ width: "6px", height: "6px", borderRadius: "3px", backgroundColor: "grey" }} isConnectable={roadmapStore.inEdit} />
                    <Handle type="source" position={Position.Top} id="t" style={{ width: "6px", height: "6px", borderRadius: "3px", backgroundColor: "grey" }} isConnectable={roadmapStore.inEdit} />
                    <Handle type="source" position={Position.Right} id="r" style={{ width: "6px", height: "6px", borderRadius: "3px", backgroundColor: "grey" }} isConnectable={roadmapStore.inEdit} />
                    <Handle type="source" position={Position.Bottom} id="b" style={{ width: "6px", height: "6px", borderRadius: "3px", backgroundColor: "grey" }} isConnectable={roadmapStore.inEdit} />
                </>
            )}
            {props.children != undefined && (
                <div>
                    {props.children}
                </div>)}
        </div>
    );
};

export default observer(NodeWrap);